package com.ebring.shareEducation.service.impl;

import com.ebring.shareEducation.bean.ScoreOrder;
import com.ebring.shareEducation.bean.User;
import com.ebring.shareEducation.bean.UserVIP;
import com.ebring.shareEducation.dao.*;
import com.ebring.shareEducation.dao.ScoreOrderMapper;
import com.ebring.shareEducation.dao.UserVIPMapper;
import com.ebring.shareEducation.service.UserVIPService;
import com.ebring.shareEducation.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class UserVIPServiceImpl implements UserVIPService {

    @Autowired
    private UserVIPMapper userVIPMapper;

    @Autowired
    private  UserMapper userMapper;

    @Autowired
    private ScoreOrderMapper scoreOrderMapper;

    @Value("${vip.generalVipPrice}")
    private String generalVipPrice;
    @Value("${vip.superVipPrice}")
    private String superVipPrice;
    //积分充值,普通会员单价
    @Value("${vip.scoreVipPrice}")
    private String scoreVipPrice;
    //积分充值,超级会员单价
    @Value("${vip.scoresuperVipPrice}")
    private String scoresuperVipPrice;

    /**
     * @param userId 用户ID
     * @param money 充值金额
     * @param vipLevel 会员类型
     * @return
     */
    @Override
    public int chargeVIP(String userId, String money, String vipLevel) {
        //是否充值过会员，若再次充值增加会员经验
        UserVIP userVIP = userVIPMapper.selectUserVip(userId);
        Double add = Double.parseDouble(money);
        if (userVIP.getVip() != null) {
            Double vip = Double.parseDouble(userVIP.getVip());
            Double total = vip + add;
            userVIP.setVip(total.toString());
        } else {
            userVIP.setVip(add.toString());
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowTime = sdf.format(new Date());
        //1普通会员 2超级会员
        try {
            if ("1".equals(vipLevel)) {
                //会员未过期 在原结束日期后续期
                if(userVIP.getVipEndtime()==null){
                    //会员未注册
                    String endTime = VipUtil.countVipEndDate(nowTime, money, generalVipPrice);
                    userVIP.setVipStarttime(nowTime);
                    userVIP.setVipEndtime(endTime);
                }else if (sdf.parse(nowTime).before(sdf.parse(userVIP.getVipEndtime()))) {
                    String endTime = VipUtil.countVipEndDate(userVIP.getVipEndtime(), money, generalVipPrice);
                    userVIP.setVipEndtime(endTime);
                } else {
                    String endTime = VipUtil.countVipEndDate(nowTime, money, generalVipPrice);
                    userVIP.setVipStarttime(nowTime);
                    userVIP.setVipEndtime(endTime);
                }
            } else if ("2".equals(vipLevel)) {
                //会员未过期 在原结束日期后续期
                if(userVIP.getVipEndtime()==null){
                    String endTime = VipUtil.countVipEndDate(nowTime, money, superVipPrice);
                    userVIP.setSupervipStarttime(nowTime);
                    userVIP.setSupervipEndtime(endTime);
                }
                if (sdf.parse(nowTime).before(sdf.parse(userVIP.getSupervipEndtime()))) {
                    String endTime = VipUtil.countVipEndDate(userVIP.getSupervipEndtime(), money, superVipPrice);
                    userVIP.setSupervipEndtime(endTime);
                }else{
                    String endTime = VipUtil.countVipEndDate(nowTime, money, superVipPrice);
                    userVIP.setSupervipStarttime(nowTime);
                    userVIP.setSupervipEndtime(endTime);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userVIPMapper.chargeVIP(userVIP);
    }

    /**
     * 查询会员状态
     *
     * @param userId
     * @return
     */
    @Override
    public RspMsg<UserVIP> selectUserVipStatus(String userId) {
        RspMsg rspMsg = new RspMsg();
        UserVIP userVIP = userVIPMapper.selectUserVip(userId);
        if (userVIP != null) {
            //判断会员类型及会员等级
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                if (userVIP.getSupervipStarttime() != null && userVIP.getSupervipEndtime() != null && userVIP.getVipStarttime() != null && userVIP.getVipEndtime() != null) {
                    Date svst = sdf.parse(userVIP.getSupervipStarttime());
                    Date svet = sdf.parse(userVIP.getSupervipEndtime());
                    Date vst = sdf.parse(userVIP.getVipStarttime());
                    Date vet = sdf.parse(userVIP.getVipEndtime());
                    if (date.after(svst) && date.before(svet)) {
                        userVIP.setVipState("2");
                    } else if (date.after(vst) && date.before(vet)) {
                        userVIP.setVipState("1");
                    } else {
                        userVIP.setVipState("0");
                    }
                } else if (userVIP.getSupervipStarttime() != null && userVIP.getSupervipEndtime() != null) {
                    Date svst = sdf.parse(userVIP.getSupervipStarttime());
                    Date svet = sdf.parse(userVIP.getSupervipEndtime());
                    if (date.after(svst) && date.before(svet)) {
                        userVIP.setVipState("2");
                    } else {
                        userVIP.setVipState("0");
                    }
                } else if (userVIP.getVipStarttime() != null && userVIP.getVipEndtime() != null) {
                    Date vst = sdf.parse(userVIP.getVipStarttime());
                    Date vet = sdf.parse(userVIP.getVipEndtime());
                    if (date.after(vst) && date.before(vet)) {
                        userVIP.setVipState("1");
                    } else {
                        userVIP.setVipState("0");
                    }
                } else {
                    userVIP.setVipState("0");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }

            rspMsg.setOK();
            rspMsg.setResult(userVIP);
        }
        return rspMsg;
    }

    // 找老师（找人才）
    @Override
    public RspMsg<User> selectTeacher(String skillsName) {
        RspMsg rspMsg = new RspMsg();
        List<User> users = userVIPMapper.selectTeacher(skillsName);
        if (users.isEmpty() || users == null) {
            rspMsg.setMsg("未找到相关数据");
        }
        rspMsg.setOK();
        rspMsg.setResult(users);
        return rspMsg;
    }

    /**
     * 会员升级
     * @param userId 用户ID
     * @return
     */
    @Override
    public int upLevelVIP(String userId) {
        int i = 0;
        UserVIP userVIP = userVIPMapper.selectUserVip(userId);
        if(userVIP!=null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            userVIP.setSupervipStarttime(sdf.format(new Date()));
            userVIP.setSupervipEndtime(userVIP.getVipEndtime());
            i = userVIPMapper.upLevelVIP(userVIP);
        }
        return i;
    }



    /**
     * 积分充值会员
     * @param userId 用户ID
     * @param money 充值金额
     * @param vipLevel 充值会员类型
     * @return
     */
    @Override
    public  RspMsg<User> ScorechargeVIP(String userId, String money, String vipLevel) {
        RspMsg rspMsg = new RspMsg();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = formatter.format(new Date());//格式化数据
        //积分流水
        ScoreOrder scoreOrder = new ScoreOrder();
        scoreOrder.setScoreId(UuidUtils.getNumberId(10));
        scoreOrder.setTradeTime(date);
        scoreOrder.setGetType("4");//获取或消费渠道 1个人信息完善 2签到 3评论 4换会员
        scoreOrder.setPlusOrMinus("0");//正负 0负 1正
        scoreOrder.setUserId(userId);
        scoreOrder.setAmount(money);
        //是否充值过会员，若再次充值增加会员经验
        User user = userMapper.selectByPrimaryKey(new User().setUserId(userId));
        if (Integer.parseInt(user.getScore())>Integer.parseInt(money)){
            user.setScore(Integer.parseInt(user.getScore())-Integer.parseInt(money)+"");//减积分
        }else {
            rspMsg.setError();
            rspMsg.setMsg("积分不足");
            return rspMsg;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowTime = sdf.format(new Date());
        //1普通会员 2超级会员
        try {
            if ("1".equals(vipLevel)) {
                //会员未过期 在原结束日期后续期
                if(user.getVipEndtime()==null){
                    //会员未注册
                    String endTime = VipUtil.countVipEndDate(nowTime, money, scoreVipPrice);
                    user.setVipStarttime(nowTime);
                    user.setVipEndtime(endTime);
                }else if (sdf.parse(nowTime).before(sdf.parse(user.getVipEndtime()))) {
                    String endTime = VipUtil.countVipEndDate(user.getVipEndtime(), money, scoreVipPrice);
                    user.setVipEndtime(endTime);
                } else {
                    String endTime = VipUtil.countVipEndDate(nowTime, money, scoreVipPrice);
                    user.setVipStarttime(nowTime);
                    user.setVipEndtime(endTime);
                }
            } else if ("2".equals(vipLevel)) {
                //会员未过期 在原结束日期后续期
                if(user.getVipEndtime()==null){
                    String endTime = VipUtil.countVipEndDate(nowTime, money, scoresuperVipPrice);
                    user.setSupervipStarttime(nowTime);
                    user.setSupervipEndtime(endTime);
                }
                if (sdf.parse(nowTime).before(sdf.parse(user.getSupervipEndtime()))) {
                    String endTime = VipUtil.countVipEndDate(user.getSupervipEndtime(), money, scoresuperVipPrice);
                    user.setSupervipEndtime(endTime);
                }else{
                    String endTime = VipUtil.countVipEndDate(nowTime, money, scoresuperVipPrice);
                    user.setSupervipStarttime(nowTime);
                    user.setSupervipEndtime(endTime);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
            scoreOrderMapper.insertSelective(scoreOrder);
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i>0){
            rspMsg.setOK();
            rspMsg.setMsg("充值成功");
        }else{
            rspMsg.setError();
            rspMsg.setMsg("充值失败");
        }
        return  rspMsg;
    }

}
